$(function() {
	OrderDetailApp.init();
	OrderDetailApp.openCoupon();
});
var OrderDetailApp = function(){
	var a=0;         //以毫秒为单位
	var s=0;
	var html;
	var btn;
	var i;
	return{
		//初始化方法
		init:function(){
				a=$("#COUNT_DOWN_TIME").val();//初始化倒计时
				s=$("#STATUS").val();
				if(s=='0'||s=='2'){
					OrderDetailApp.countdown();
					
				};
		},
		//砍价倒计时
		countdown:function(){
			if(a<=0){
				return false;
			}
		        a=a-1000;
		        var b=new Date();
		        b.setTime(0);
		        var c=new Date();
		        c.setTime(a);
		        var day1=b.getDate();        //为方便调用，把天数、小时等单独定义
		        var hours1=b.getHours();
		        var minu1=b.getMinutes();
		        var seco1=b.getSeconds();
		        var day2=c.getDate();
		        var hours2=c.getHours();
		        var minu2=c.getMinutes();
		        var seco2=c.getSeconds();
		        var day=day2-day1;
		        var hours=hours2-hours1;
		        var minu=minu2-minu1;
		        var seco=seco2-seco1;
		        hours=hours+day*24;
		        if(s=='0'){
		        document.getElementById('minua').innerHTML=minu;
		        document.getElementById('secoa').innerHTML=seco;
		        }else{
		       	document.getElementById('daya').innerHTML=day;
		        }
		      
//		        document.getElementById('hoursa').innerHTML=hours;
		       
		        setTimeout("OrderDetailApp.countdown()",1000);
		},
		/**
		 * 支付
		 */
		pay:function(id){
			var url = window.location.href;
			url = encodeURI(url);
			window.location.href = $("#APP_ROOT_PATH").val() + 'pay/pay?orderId=' + id + "&redirectUrl=" + url;
		},
		/**
		 * 订单确认页支付
		 */
		confirmPay:function(id){
		/*	var flag = $("#payCheck").hasClass('on-checked');
			if(!flag){
				layer.open({
				    content: '请勾选支付方式',
				    skin: 'msg',
				    time: 2 //2秒后自动关闭
				  });
				return;
			}*/
			
			var goodsList = $(".goodsList");
			if(goodsList.size() <=0){
				layer.open({
					    content: "没有选择商品",
					    skin: 'msg',
					    time: 2 //2秒后自动关闭
					  });
				return false;
			}
			var aId = $("#aId").val();
			var datas = new Array();
			for(var i = 0;i<goodsList.length;i++){
				var goods = $(goodsList[i]);
				var goodsId = $(goods).find("input[name='goodsId']").val();
				var num = $(goods).find("input[name='num']").val();
				
				var data = {id:parseInt(goodsId),num:parseInt(num)};
				datas.push(data);
			}
			
			//优惠券ID
			var cId = $("#dis_id").val();
			
			var json = {json:JSON.stringify(datas),aId:aId,cId:cId};
			if(aId == undefined || aId == ""){
				layer.open({content: '请选择收货地址',skin: 'msg',time: 2});
				return false;
			}
			var url = $("#APP_ROOT_PATH").val() + 'order/add';
			mui.util.Ajax.asyncGET(url,json,function(res){
				layer.closeAll();
				if(res.ret != undefined && res.ret != 0){
					layer.open({
					    content: res.message,
					    skin: 'msg',
					    time: 2 //2秒后自动关闭
					  });
					return;
				}
				
				if(res > 0){
					var url = window.location.href;
					url = encodeURI(url);
					window.location.href = $("#APP_ROOT_PATH").val() + 'pay/pay?orderId=' + res + '&redirectUrl=' + url;
				}else{
					layer.open({
					    content: '订单新增失败，请刷新重试',
					    skin: 'msg',
					    time: 2 //2秒后自动关闭
					  });
				}
			},function(){
				layer.closeAll();
			},function(){
				layer.open({type: 2});
			});
		},
		/**
		 * 订单确认页支付
		 */
		discountConfirmPay:function(id){
			var flag = $("#payCheck").hasClass('on-checked');
			if(!flag){
				layer.open({
				    content: '请勾选支付方式',
				    skin: 'msg',
				    time: 2 //2秒后自动关闭
				  });
				return;
			}
			
			var goodsList = $("div.order-body");
			var aId = $("#aId").val();
			
			var recordId = $(goodsList[0]).find("input[name='recordId']").val();
			
			//使用优惠券ID
			var cId = $("#dis_id").val();
			
			var json = {discountId:recordId,aId:aId,cId:cId};
			if(aId == undefined || aId == ""){
				layer.open({content: '请选择收货地址',skin: 'msg',time: 2});
				return false;
			}
			
			var url = $("#APP_ROOT_PATH").val() + 'order/add_discount';
			mui.util.Ajax.asyncGET(url,json,function(res){
				layer.closeAll();
				if(res.ret != undefined && res.ret != 0){
					layer.open({
					    content: res.message,
					    skin: 'msg',
					    time: 2 //2秒后自动关闭
					  });
					return;
				}
				
				if(res > 0){
					var url = window.location.href;
					url = encodeURI(url);
					window.location.href = $("#APP_ROOT_PATH").val() + 'pay/pay?orderId=' + res + '&redirectUrl=' + url;
				}else{
					layer.open({
					    content: '订单新增失败，请刷新重试',
					    skin: 'msg',
					    time: 2 //2秒后自动关闭
					  });
				}
			},function(){
				layer.closeAll();
			},function(){
				layer.open({type: 2});
			});
		},
		cancelOrder:function(id){
			layer.open({
			    content: '您确定取消订单吗!',
			    btn: ['确定', '取消'],
			    yes: function(index){
			    	var url = $("#APP_ROOT_PATH").val() + 'order/set_cancel';
				       var data = {orderId:id};
						mui.util.Ajax.asyncGET(url,data,function(res){
							layer.close(index);
							if(res.ret != undefined && res.ret != 0){
								layer.open({
								    content: res.message,
								    skin: 'msg',
								    time: 2 //2秒后自动关闭
								  });
								return;
							}
							if(res){
								window.location.reload();
							}else{
								layer.open({
								    content: '操作失败',
								    skin: 'msg',
								    time: 2 //2秒后自动关闭
								  });
							}
						},function(){layer.close(index);});
			    }
			  });
		},
		/**
		 * 设置为已收货
		 */
		setReceive:function(id){
			layer.open({
			    content: '您确定已收到该商品吗!',
			    btn: ['确定', '取消'],
			    yes: function(index){
			    	var url = $("#APP_ROOT_PATH").val() + 'order/set_receive';
					var data = {orderId:id};
					mui.util.Ajax.asyncGET(url,data,function(res){
						layer.close(index);
						if(res.ret != undefined && res.ret != 0){
							layer.open({
							    content: res.message,
							    skin: 'msg',
							    time: 2 //2秒后自动关闭
							  });
							return;
						}
						if(res){
							window.location.reload();
						}else{
							layer.open({
							    content: '操作失败',
							    skin: 'msg',
							    time: 2 //2秒后自动关闭
							 });
						}
					},function(){layer.close(index);});
			    }});
		},
		/**
		 * 再来一单
		 */
		next:function(id){
			var url = $("#APP_ROOT_PATH").val() + 'order/get_confirm_data';
			var data = {orderId:id};
			mui.util.Ajax.asyncGET(url,data,function(res){
				layer.closeAll();
				if(res.ret != undefined && res.ret != 0){
					layer.open({
					    content: res.message,
					    skin: 'msg',
					    time: 2 //2秒后自动关闭
					  });
					return;
				}
				var json = encodeURI(res);
				var url = $("#APP_ROOT_PATH").val() + 'order/confirm?json=' + json;
				window.location.href = url;
			},function(){
				layer.closeAll();
			},function(){
				layer.open({type: 2});
			});
		},
		initConfirm:function(){
			$(".u4-i1").click(function(e){
				e.preventDefault();
			    if($(this).prev().hasClass("unchecked")){
			        $(this).prev().addClass("on-checked").removeClass("unchecked");
			    }else{
			        $(this).prev().addClass("unchecked").removeClass("on-checked");
			    }
			});
			
			
			
		},
		selectAddress:function(){
			var url = window.location.href;
			
			var json = $("#json").val();
			if(json != undefined && json !=""){
				window.location.href = $("#APP_ROOT_PATH").val() + 'order/select_address?json=' + json;
			}else{
				var index = url.indexOf("&aId");
				if(index != -1){
					var nUrl = url.substring(0,index);
					url = url.substring(index + "&aId".length,url.length - 1);
					var lastIndex = url.indexOf("&");
					if(lastIndex != -1){
						url = url.substring(lastIndex,url.length - 1);
						nUrl = nUrl + url;
					}
					window.location.href = $("#APP_ROOT_PATH").val() + 'order/select_address?redirectUrl=' + encodeURI(nUrl);
				}else{
					window.location.href = $("#APP_ROOT_PATH").val() + 'order/select_address?redirectUrl=' + encodeURI(url);
				}
				
			}
		},
		//优惠券弹层
		openCoupon:function(){
			var pCount = 0;
			
			$("#coupon").on("click",function(){
				var totalAmount = $("#tAmount").val();
				$("body").css("overflow","hidden");
				
				var goodsArray = $("input[name=goodsId]");
				var goodsIds = new Array();
				for(var i = 0;i < goodsArray.length;i++){
					goodsIds.push($(goodsArray[i]).val());
				}
				
				var goodsIdStr = goodsIds.join(',');
				
				btn = $(this);
				var url = $("#APP_ROOT_PATH").val() + "coupon/list_my_coupon?amount=" + totalAmount + "&goodsIds=" + goodsIdStr;
	            mui.util.Ajax.asyncGET(
	                url, null,
	                function(data) {
	                    layer.closeAll();
	                    if(data.length > 0) {
	                        var jsonData = {
	                            "data": data
	                        };
	                        var bt = baidu.template;
	                        htmlStr = bt('t:coupon', jsonData);
	                        
	                        layer.open({
				                type: 1
				                ,content:htmlStr
				                ,btn:'关闭'
				                ,yes: function(index, layero){
			                		$("body").css("overflow","auto");
			                		layer.closeAll();
			                	 }
				                ,anim: 'up'
				                ,shadeClose: false
				                ,style: 'position:fixed; bottom:0; left:0; width: 100%; height: 40px;  padding:10px 0; border:none;'
				            });
				            
				            $(".frm_radio_label").on("click",function(){
				            	
								$(this).addClass('selected');
						        $(this).parent().parent().siblings().find('.frm_radio_label').removeClass('selected');
						        
						        var tmp = $(this).find("#radio").val();
						        $("#dis_id").val($(this).find("#radio_id").val());
						        var couponPrice = $(this).find("#radio_price").val();
						        $("#dis_price").val(couponPrice);
						        
						        var amount = 0;
						        var oriAmount = parseFloat($("#aAmount").val());
						        couponPrice = parseFloat(couponPrice);
						        
						        if(couponPrice == 0){
						        	$("#totalAmount").text(oriAmount);
						        	$("#sTotalAmount").text(oriAmount);
							        $("#radio_price").text(0);
						        }else{
						        	if(oriAmount < couponPrice){
							        	$("#totalAmount").text(0);
							        }else{
							        	amount = oriAmount - couponPrice;
							        	amount = Math.round(amount*100)/100;
							        	$("#totalAmount").text(amount);
							        }
							        $("#sTotalAmount").text(amount);
							        $("#radio_price").text(amount);
						        }
						        
						        $("#coupDetail").text(tmp);
						        layer.closeAll();
						        $("body").css("overflow","auto");
							});
				            
	                    }
	                },
	                function() {
	                    layer.closeAll();
	                },
	                function() {

	                }
	            )
			})
		}
	}
}();

